<?php
require_once __DIR__.'/../config/config_ucenter.php';
require __DIR__.'/../source/class/class_core.php';
C::app()->init();

// error_reporting(1);

$method = $_REQUEST['action'];
if (!method_exists('JosnData', $method)) {
    echo json_encode(array(
        'status' => 0,
        'error'  => 'Parameter error, method does not exist .'
    ));
    exit;
}
$params = $_REQUEST;

$json = new JosnData($params);
$json->$method();




/**
 *
 */
class JosnData
{
    protected $params;
    protected $uid=0;
    protected $access_token='';
    protected $errnums = 0;
    protected $urlbase='https://att.pindiy.com/data/attachment/';
    protected $ossurl='https://attpindiydz.oss-accelerate.aliyuncs.com/data/attachment/';
    protected $allowshow=[
        // 279,
        133,
        // 266,
        // 267,
        // 83,
        89,
        197,
        285,
        288,
        287,
        269,
        271,
        273,
        275,
        283,
        277
    ];
    public function __construct($params = array())
    {
        $params['page']=$params['page']>0?$params['page']:1;
        $params['size']=$params['size']>0?$params['size']:20;
        $access_token=isset($_REQUEST['access_token'])?$_REQUEST['access_token']:'';
        $uid=isset($_REQUEST['uid'])?$_REQUEST['uid']:0;
        if($uid>0 && $access_token){
            $str=authcode(preg_replace('/(plusadd)/ism','+',$access_token),'DECODE','webapp',864000);
            if(!$str){
                $this->json(1,'Login verification error, please login again');
            }
            $arr=explode(':',$str);
            if(!$arr || $arr[0]!=$uid){
                $this->json(1,'Login Error');
            }else if($arr[1]+864000<time()){
                $this->json(1,'Login expired, please login again');
            }
            $this->uid=$uid;
            $this->access_token=$access_token;
        }
        // $this->json(1,'登录校验出错，请重新登录:'.$uid.':'.$access_token,$this->params);
        $this->params = $params;
    }
    
    // 获取广告设置
    public function getadids(){
        $data=parse_ini_file(__DIR__.'/adids.ini',true);
        $result=[
            'hengfu'=>['android'=>'','ios'=>''],
            'buylist'=>''
        ];
        
        foreach ($data as $k=>$v){
            // 内购项目
            if(stripos($k,'buylist')!==false){
                $v['day']=(int)$v['day'];
                $v['index']=(int)$v['index'];
                $result['buylist'][]=$v;
                continue;
            }
            // 横幅广告
            if($k=='hengfu'){
                foreach ($v as $os=>$id){
                    if(stripos($os,'android')===0){
                        $result['hengfu']['android'][]=$id;
                    }else{
                        $result['hengfu']['ios'][]=$id;
                    }
                }
                continue;
            }
            // task ids
            foreach ($v as $num=>$id){
                $result[$k][]=['adid'=>$id,'mount'=>$num];
            }
        }
        $this->json(0,'ok',$result);
    }
    
    //根据相关参数组合筛选帖子
    public function getThreadListBy(){
        global $_G;
        
        $imgurlbase=$this->urlbase;
        $isvip=false;
        if($this->uid>0){
            $vip=$this->getpay($this->uid);
            if($vip && $vip['endtime']>time()){
                $isvip=true;
                $imgurlbase=$this->ossurl;
            }
        }

        // 获取条件
        $where=[
            't.'.DB::field('fid',$this->allowshow,'in')
        ];
        // 排序规则
        $order=[];
        // 是否按照版块选取
        if($this->params['fid']){
            $where[]='t.'.DB::field('fid',intval($this->params['fid']),'=');
        }
        
        // 是否精华
        if($this->params['digest']>0){
            $where[]='t.'.DB::field('digest',0,'>');
            $order[]='t.'.DB::order('digest','desc');
        }
        // 是否高亮
        if($this->params['highlight']>0){
            $where[]='t.'.DB::field('highlight',0,'>');
        }
        // 是否平分
        if($this->params['rate']>0){
            $where['rate']='t.'.DB::field('t.rate',0,'>');
            $order[]='t.'.DB::order('rate ','desc');
        }
        
        $where[]='t.'.DB::field('closed',0);

        // 开始排序规则
        // 回复次数
        if($this->params['replies']){
            $order[]='t.'.DB::order('replies','desc');
        }
        // 浏览次数
        if($this->params['views']){
            $order[]='t.'.DB::order('views','desc');
        }
        // 推荐指数 recommends
        if($this->params['recommends']){
            $order[]='t.'.DB::order('recommends','desc');
        }
        // 热度值 heats
        if($this->params['heats']){
            $order[]='t.'.DB::order('heats','desc');
        }
        // 收藏次数 favtimes
        if($this->params['favtimes']){
            $order[]='t.'.DB::order('favtimes','desc');
        }
        
        // 点评数 comments
        if($this->params['comments']){
            $order[]='t.'.DB::order('comments','desc');
        }
        
        
        // 最后回复时间
        if($this->params['lastpost']){
            $order[]='t.'.DB::order('lastpost','desc');
        }
        // 最后再按发布时间倒序
        $order[]='t.'.DB::order('dateline','desc');

        // 获取条数
        $page=(int)$this->params['page']?$this->params['page']:1;
        $size=(int)$this->params['size']?$this->params['size']:20;
        $start=($page-1)*$size;
        
        $fidjson=$this->getForumsname();
        try {
            $redis= new \Redis;
            $redis->connect('127.0.0.1',6379);
            $notids=$redis->smembers('jubaotidlist');
            $notids=$notids?$notids:[0];
        } catch (\Exception $e) {
            $notids=[0];
        }
        
        $data=DB::fetch_all("select t.*,p.invisible,p.message from %t as t inner join %t as p on t.tid=p.tid WHERE ".implode(' AND ',$where).' and p.invisible>=%d  and p.position=%d and t.fid !=%d and t.'.DB::field('tid',$notids,'notin').' ORDER BY '.implode(',',$order). ' LIMIT %d,%d',array('forum_thread','forum_post',0,1,90,$start,$size),'tid');
        
        if($this->params['summary']>0){
            foreach ($data as $k=>$v){
                $data[$k]['forumname']=$fidjson[$v['fid']]['name'];
                $tmp=preg_replace(array('/\[.*?\]/ism','/&#.*?;/ism','/\s\d{4}\-\d{1,2}\-\d{1,2} \d{2}:\d{2}/i'),array('','',''),strip_tags($v['message']));
                
                $data[$k]['summary']=mb_substr($tmp,0,30);
                $data[$k]['author']='';
                $fm=DB::result_first('select attachment from %t WHERE tid=%d',array('forum_threadimage',$v['tid']));
                $data[$k]['cover']=$fm?($imgurlbase.'forum/'.$fm):'';
                preg_match('/\[attach.*?\](\d+)\[/i',$v['message'],$m);
                if(!$data[$k]['cover'] && $m[1]){
                    $tabid=DB::result_first('select tableid from %t WHERE aid=%d',array('forum_attachment',$m[1]));
                    if($tabid === 0  ||  ($tabid && $tabid!=127)){
                        $cover=DB::result_first('select attachment from %t WHERE aid=%d',array('forum_attachment_'.$tabid,$m[1]));
                        if(preg_match('/(\.jpg)|(\.png)|(\.jpeg)/i',$cover)){
                            if(!preg_match('/^http/i',$cover)){
                               $cover=$imgurlbase.'forum/'.$cover;
                            }
                            $data[$k]['cover']=$cover;
                        }
                    }
                }
                if(!$data[$k]['cover'] &&  $allaids=DB::fetch_all('select * from %t where tid=%d and uid=%d ORDER by  aid  limit 20 ',array('forum_attachment',$v['tid'],$v['authorid']))){
                    foreach ($allaids as $av){
                        $tmp=DB::fetch_first('select attachment,filename from %t WHERE aid=%d',array('forum_attachment_'.$av['tableid'],$av['aid']));
                        if(preg_match('/(\.jpg)|(\.png)|(\.jpeg)/i',$tmp['attachment'])){
                            $data[$k]['cover']=preg_match('/^https?/i',$tmp['attachment'])?$tmp['attachment']:($imgurlbase.'forum/'.$tmp['attachment']);
                            break;
                        }
                    }
                    
                }
                $data[$k]['cover']=$data[$k]['cover']?preg_replace('/https:\/\/img\.pindiy\.com\/data\/attachment\//i',$imgurlbase,$data[$k]['cover']):'';
                if($data[$k]['cover'] && $isvip && stripos($data[$k]['cover'],$imgurlbase)===false){
                    $data[$k]['cover']=preg_replace('/https:\/\/att\.pindiy\.com\/data\/attachment\//i',$imgurlbase,$data[$k]['cover']);
                }
                
            }
        }
        $this->json(0,'ok',array_values($data));
    }
    
    public function getForumsname(){
        $fidjson=file_get_contents(__DIR__.'/fid.json');
        if($fidjson){
            $fidjson=json_decode($fidjson,true);
            if($fidjson){
                return $fidjson;
            }
        }
        if(!$fidjson){
            $fidjson=C::t('forum_forum')->fetch_all_by_status(1);
            $fiddata=[];
            foreach ($fidjson as $v){
                // if(in_array(intval($v['fid']),$this->allowshow)){
                    $fiddata[$v['fid']]=$v;
                // }
            }
            $fidjson=$fiddata;
            unset($fiddata);
            file_put_contents(__DIR__.'/fid.json',json_encode($fidjson));
        }
        return $fidjson;
    }
    public function ceshi2(){
        header('Content-Type:application/json;charset=utf-8');
        print_r($this->getForumsname());
    }
    // 获取最新发表的帖子的快捷查询方式，实际调用 $this->getThreadListBy
    // page size fid 
    public function getThreadListByNew(){
        $this->params=[
          "fid"=>$this->params['fid'],
          "page"=>$this->params['page'],
          "size"=>$this->params['size'],
          "dateline"=>1,
          'summary'=>$this->params['summary']?1:0
        ];
        return $this->getThreadListBy();
    }
    
     // 获取最后回复的的帖子的快捷查询方式，实际调用 $this->getThreadListBy
    // page size fid 
    public function getThreadListByLastpost(){
        $this->params=[
          "fid"=>$this->params['fid'],
          "page"=>$this->params['page'],
          "size"=>$this->params['size'],
          "lastpost"=>1,
          'summary'=>$this->params['summary']?1:0
        ];
        return $this->getThreadListBy();
    }
    
    // 获取精华帖子的快捷查询方式，实际调用 $this->getThreadListBy
    // page size fid 
    public function getThreadListByDigest(){
        $this->params=[
          "fid"=>$this->params['fid'],
          "page"=>$this->params['page'],
          "size"=>$this->params['size'],
          "digest"=>1,
          'summary'=>$this->params['summary']?1:0
        ];
        return $this->getThreadListBy();
    }
    
    // 首页6个元素，根据 1-6
    /**
    tabList: [{
          id: "tab01",
          name: '最新帖子',//最后回复时间 lastpost 倒序
          newsid: 1
        }, {
          id: "tab02",
          name: '最多访问',//views 倒序
          newsid: 2
        }, {
          id: "tab03",
          name: '最多回复',//replies 倒序
          newsid: 3
        }, {
          id: "tab04",
          name: '最多收藏',//favtimes倒序
          newsid: 4
        }, {
          id: "tab05",
          name: '热度',// heats 倒序
          newsid: 5
        }, {
          id: "tab06",
          name: '推荐',//recommends 倒序
          newsid: 6
        }],
    */
    public function getIndex(){
        $con=[
            1=>'dateline',
            2=>'views',
            3=>'replies',
            4=>'favtimes',
            5=>'heats',
            6=>'recommends'
        ];
        $this->params=[
          "fid"=>$this->params['fid'],
          "page"=>$this->params['page'],
          "size"=>$this->params['size'],
          $con[$this->params['type']] =>1,
          'summary'=>$this->params['summary']?1:0
        ];
        
        return $this->getThreadListBy();
    }
    
    
    // 根据tid获取帖子正文信息
    public function getBodyByTid(){
        global $_G;
        $imgurlbase=$this->urlbase;
        $isvip=false;
        if($this->uid>0){
            $vip=$this->getpay($this->uid);
            if($vip && $vip['endtime']>time()){
                $isvip=true;
                $imgurlbase=$this->ossurl;
            }
        }
        // 获取一楼正文帖子
        $data=C::t('forum_post')->fetch_all_by_tid_position(0,$this->params['tid'],1);
        if($data && $data[0]){
            require_once libfile('function/discuzcode');
            // 处理附件及附件图片
            $hasaid=[];
            $fujian=$tupian=[];
            // 处理 [attach] [attchimg] 
            $data[0]['message']=preg_replace_callback('/\[attach.*?\](\d+)\[\/attach.*?\]/ism',function($m) use($imgurlbase,&$hasaid,&$fujian,&$tupian){
                $tabid=DB::result_first('select tableid from %t WHERE aid=%d',array('forum_attachment',$m[1]));
                $hasaid[]=(int)$m[1];
                if($tabid == 0  ||  ($tabid && $tabid!=127)){
                    $tmp=DB::fetch_first('select attachment,filename from %t WHERE aid=%d',array('forum_attachment_'.$tabid,$m[1]));
                    if(!preg_match('/(\.jpg)|(\.png)|(\.jpeg)/i',$tmp['attachment'])){
                        $fujian[]=['url'=>$imgurlbase.'forum/'.$tmp['attachment'],'name'=>urlencode($tmp['filename'])];
                        return '';
                    }
                    $tupian[]=preg_match('/^https?/i',$tmp['attachment'])?$tmp['attachment']:($imgurlbase.'forum/'.$tmp['attachment']);
                    return '';
                }
            },$data[0]['message']);
            
            // 处理 [img]
            preg_replace_callback('/\[img.*?\](.*?)\[\/img\]/ism', function($m) use(&$tupian){
                if($m[1]){
                    $tupian[]=preg_match('/^https?/i',$m[1])?$m[1]:($imgurlbase.$m[1]);
                }
                return '';
            },$data[0]['message']);
            
            $data[0]['message']=discuzcode($data[0]['message'],false, false, 1, 1, 1, 1, 1,0, 0,/*authorid*/'0', 1, /*pid*/0,  0,  0, 1);
            $data[0]['message']=htmlspecialchars_decode($data[0]['message']);
             
            // 处理 <img>
            $data[0]['message']=preg_replace_callback('/<img.*?src="(.*?(jpg|png|jpeg))"[^>]*?>/ism', function($m) use(&$tupian){
                if($m[1]){
                    $tupian[]=preg_match('/^https?/i',$m[1])?$m[1]:($imgurlbase.$m[1]);
                    return '';
                }else{
                    return '<img src="'.$m[1].'">';
                }
            },$data[0]['message']);
           
            
            // 获取没有被包含在 message 里的附件486140
            $allaids=DB::fetch_all('select * from %t where tid=%d ORDER by  aid desc limit 50 ',array('forum_attachment',$this->params['tid']));
            $num=0;
            foreach ($allaids as $v){
                if($num>10){
                    break;
                }
                if(!in_array($v['aid'],$hasaid)){
                    $tmp=DB::fetch_first('select attachment,filename from %t WHERE aid=%d',array('forum_attachment_'.$v['tableid'],$v['aid']));
                    if(!preg_match('/(\.jpg)|(\.png)|(\.jpeg)/i',$tmp['attachment'])){
                        $fujian[]=['url'=>$imgurlbase.'forum/'.$tmp['attachment'],'name'=>urlencode($tmp['filename'])];
                    }else{
                        $num++;
                        $tupian[]=preg_match('/^https?/i',$tmp['attachment'])?$tmp['attachment']:($imgurlbase.'forum/'.$tmp['attachment']);
                    }
                }
            }
            $data[0]['message']=strip_tags($data[0]['message']);
            $data[0]['message']=preg_replace('/\s\d{4}\-\d{1,2}\-\d{1,2} \d{2}:\d{2}/i','',$data[0]['message']);
            
            $data[0]['fujian']=[];
            
            if($tupian){
                foreach ($tupian as $itu=>$tu){
                    $tupian[$itu]=preg_replace('/https:\/\/img\.pindiy\.com\/data\/attachment\//i',$imgurlbase,$tu);
                    if($isvip && stripos($tupian[$itu],$imgurlbase)===false){
                        $tupian[$itu]=preg_replace('/https:\/\/att\.pindiy\.com\/data\/attachment\//i',$imgurlbase,$tupian[$itu]);
                    }
                }
            }
            $data[0]['tupian']=$tupian;

            
            
            $sortid=DB::result_first('select sortid from %t WHERE tid=%d',array('forum_thread',$data[0]['tid']));
            // 处理分类信息
            if($sortid>0){
                $content=DB::fetch_all('select * from %t WHERE tid=%d and sortid=%d',array('forum_typeoptionvar',$data[0]['tid'],$sortid),'optionid');
                if($content){
                    // 获取所有 optionid 的规则记录和类型
                    $options=DB::fetch_all('select title,optionid,rules,type from %t WHERE '.DB::field('optionid',array_keys($content),'in'),array('forum_typeoption'),'optionid');
                    if($options){
                        foreach ($options as $k=>$v){
                            // 遍历规则类型，name即为 该项规则显示名称
                            $content[$k]['name']=$v['title'];
                            // 如果是radio checkbox select ,需要再次匹配规则中内容提取，否则不需要动
                            if(in_array($v['type'],['radio','checkbox','select'])){
                                // 以 \t 切割 content[$k]['value']，获取匹配规则中的某项
                                $val=explode("\t",$content[$k]['value']);
                                
                                // 将规则转为 以 设定的1=内容形式
                                $rules=explode("\n",trim(unserialize($v['rules'])['choices']));
                                $rulesarr=[];
                                array_map(function($item) use(&$rulesarr){
                                	$tmp=explode("=", trim($item));
                                	$rulesarr[$tmp[0]]=$tmp[1];
                                	return '';
                                },$rules);
                                $value=$content[$k]['value'];
                                $content[$k]['value']=[];
                                // 遍历所选
                                foreach ($val as $rulekey){
                                    $content[$k]['value'][]=$rulesarr[$rulekey];
                                }
                                $content[$k]['value']=implode(', ',$content[$k]['value']);
                            }
                        }
                        $data[0]['fenlei']=array_values($content);
                    }
                }
            }
            
            $data[0]['hasfavore']=DB::result_first('select count(favid) from %t WHERE id=%d and uid=%d and idtype=%s',array('home_favorite',$data[0]['tid'],$this->uid,'tid'));
        }
        $data[0]['author']='PinDIY';
        $fidjson=$this->getForumsname();
        $data[0]['forumname']=$fidjson[$data[0]['fid']]['name'];
        $this->json(0,'ok',$data[0]);
    }
    
    // 获取回复，从2楼开始
    public function getPostByTid(){
        global $_G;
        $imgurlbase=$this->urlbase;
        require_once libfile('function/discuzcode');
        // 获取条数
        $page=(int)$this->params['page']?$this->params['page']:1;
        $size=(int)$this->params['size']?$this->params['size']:20;
        $start=($page-1)*$size;
        $data=DB::fetch_all('select * from %t WHERE tid=%d and '.DB::field('position',"1",'<>').' order by dateline desc limit %d,%d',array('forum_post',$this->params['tid'],$start,$size));
        $allauthorid=[];
        foreach ($data as $k=>$v){
            $allauthorid[$v['authorid']]=$v['authorid'];
            $tupian=[];
            // // 处理附件及附件图片
            $v['message']=preg_replace_callback('/\[attach.*?\](\d+)\[\/attach.*?\]/ism',function($m) use($imgurlbase,&$tupian){
                $tabid=DB::result_first('select tableid from %t WHERE aid=%d',array('forum_attachment',$m[1]));
                if($tabid == 0  ||  ($tabid && $tabid!=127)){
                    $tmp=DB::fetch_first('select attachment,filename from %t WHERE aid=%d',array('forum_attachment_'.$tabid,$m[1]));
                    if(preg_match('/(\.jpg)|(\.png)|(\.jpeg)/i',$tmp['attachment'])){
                      $tupian[]=$imgurlbase.'forum/'.$tmp['attachment'];
                    }
                    return '';
                }
            },$v['message']);
            
            $v['message']=preg_replace_callback('/\[img.*?\](.*?(jpg|png))\[\/img\]/ism', function($m,&$tupian){
                $tupian[]=$m[1];
                return  '';
            },$v['message']);

            $v['message']=discuzcode($v['message'],false, false, 1, 1, 1, 1, 1,0, 0,/*authorid*/'0', 1, /*pid*/0,  0,  0, 1);
            $data[$k]['message']= preg_replace([
                '/\[\w+.*?\].*?\[\/\w+.*?\]/ism'
            ],[''],strip_tags($v['message']));
            $data[$k]['tupian']=[];
            $avatar=avatar($v['authorid'],'small',true);
            if(!is_file(DISCUZ_ROOT.substr($avatar, stripos($avatar, '.com')+4))){
                $avatar='https://www.pindiy.com/uc_server/images/noavatar_small.gif';
            }
            $data[$k]['avatar']=$avatar;
        }
        // 获取当前有效的vip
        $allvip=DB::fetch_all('select * from '.DB::table('appvip').' where  '.DB::field('endtime',time(),'>').' and  '.DB::field('uid',$allauthorid,'in'),array(),'uid');
        if($allvip){
            foreach ($data as $k=>$v){
                if(isset($allvip[$v['authorid']])){
                    $data[$k]['vip']='vip'.$allvip[$v['authorid']]['type'];
                }
            }
        }

        $this->json(0,'ok',array_values($data));
    }
    
    
    

    // 获取全部版块信息
    /**
    fid=>[
        分区信息..
        分区信息..
        forum=>[
            版块信息..
            版块信息..
            forumfield=>[
                扩展信息..
                扩展信息..
            ]
            sub=>[
                子版块信息..
                子版块信息..
                forumfield=>[
                    扩展信息..
                    扩展信息..
                ]
            ]
        ]

    ]
    */
    public function getForumsoldno(){
        $data=[];
        // 获取所有分区 版块 子版块
        $list=C::t('forum_forum')->fetch_all_by_status(1);
        // 记录版块对应的分区，以便正确将sub子版块插入
        $fid2fup=[];
        // 记录版块和子版块fid，获取扩展信息
        $fids=[];
        // 基url，用于图标 图片等补全
        $url=$this->urlbase;
        $fiddata=[];
        foreach ($list as $k=>$v){
            // 分区
            if($v['type']=='group'){
                $data[$v['fid']]=$v;
            }else if($v['type']=='forum'){
                // 直接版块
                if(in_array($v['fid'],$this->allowshow)){
                    $data[$v['fup']]['forum'][$v['fid']]=$v;
                    $fid2fup[$v['fid']]=$v['fup'];
                    $fids[]=$v['fid'];
                }
                
            }else if($v['type']=='sub'){
                // 子版块
                if(in_array($v['fid'],$this->allowshow)){
                    $data[$fid2fup[$v['fup']]]['forum'][$v['fup']]['sub'][$v['fid']]=$v;
                    $fids[]=$v['fid'];
                }
                
            }
            
            
            $fiddata[$v['fid']]=$v;
            
        }
        file_put_contents(__DIR__.'/fid.json',json_encode($fiddata));
        unset($list);
        $data=array_values($data);
        foreach ($data as $k=>$v){
            if($v['forum']){
                foreach ($v['forum'] as $k2=>$v2){
                    if($v2['sub']){
                        $v['forum'][$k2]['sub']=array_values($v['forum'][$k2]['sub']);
                    }
                    $v['forum'][$k2]['cover']=DB::result_first('SELECT icon from %t WHERE fid=%d',array('forum_forumfield',$v2['fid']));
                }
                $data[$k]['forum']=array_values($v['forum']);
            }
        }
        $this->json(0,'ok',$data);
    }
    
    public function getForums(){
        $data=[];
        // 获取所有分区 版块 子版块
        $list=C::t('forum_forum')->fetch_all_by_status(1);
        // 记录版块对应的分区，以便正确将sub子版块插入
        $fid2fup=[];
        // 记录版块和子版块fid，获取扩展信息
        $fids=[];
        // 基url，用于图标 图片等补全
        $url=$this->urlbase;
        $fiddata=[];
        
        foreach ($list as $k=>$v){
            // 分区
            if($v['type']=='group'){
                $data[$v['fid']]=$v;
            }else if($v['type']=='forum'){
                // 直接版块
                if(in_array($v['fid'],$this->allowshow)){
                    // echo "{$v['fid']}\n";
                    $data[$v['fup']]['forum'][$v['fid']]=$v;
                    $fid2fup[$v['fid']]=$v['fup'];
                    $fids[]=$v['fid'];
                }
                
            }else if($v['type']=='sub'){
                // 子版块
                if(in_array($v['fid'],$this->allowshow)){
                    $data[$fid2fup[$v['fup']]]['forum'][$v['fup']]['sub'][$v['fid']]=$v;
                    $fids[]=$v['fid'];
                }
                
            }
            $fiddata[$v['fid']]=$v;
        }
        // print_r($data);
        // exit;
        file_put_contents(__DIR__.'/fid.json',json_encode($fiddata));
        unset($list);
        $data=array_values($data);
        $newdata=[];
        foreach ($data as $k=>$v){
            if($v['forum']){
                foreach ($v['forum'] as $k2=>$v2){
                    if($v2['sub']){
                        $v['forum'][$k2]['sub']=array_values($v['forum'][$k2]['sub']);
                    }
                    $v['forum'][$k2]['cover']=DB::result_first('SELECT icon from %t WHERE fid=%d',array('forum_forumfield',$v2['fid']));
                }
                $data[$k]['forum']=array_values($v['forum']);
                $newdata[]=$data[$k];
            }
        }
        $this->json(0,'ok',$newdata);
    }
    
    // 获取我收藏的帖子
    public function getMyFavores(){
        if($this->uid<1){
            $this->json(1,'login again');
        }
        $start=($this->params['page']-1)*$this->params['size'];
        $data=DB::fetch_all('SELECT * from %t WHERE idtype=%s and uid=%d order by dateline desc limit %d,%d',array('home_favorite','tid',$this->uid,$start,$this->params['size']));
        if(!$data){
            $this->json(1,'no data');
        }
        $this->json(0,'ok',$data);
    }
    
    // 获取我发布的帖子
    public function getMyThread(){
        if($this->uid<1){
            $this->json(1,'login again');
        }
        $start=($this->params['page']-1)*$this->params['size'];
        $data=DB::fetch_all('SELECT * from %t WHERE authorid=%d order by dateline desc limit %d,%d',array('forum_thread',$this->uid,$start,$this->params['size']));
        if(!$data){
            $this->json(1,'No post yet');
        }
        return $this->json(0,'ok',$data);
    }
    // 获取我参与的帖子
    public function getMyPost(){
        if($this->uid<1){
            $this->json(1,'login again');
        }
        $start=($this->params['page']-1)*$this->params['size'];
        $data=DB::fetch_all('SELECT t.subject as threadsubject,p.* from %t as t  inner join %t as p on t.tid=p.tid WHERE t.authorid!=%d and p.authorid=%d and p.'.DB::field('position','1','<>').' order by p.dateline desc limit %d,%d',array('forum_thread','forum_post',$this->uid,$this->uid,$start,$this->params['size']));
        if(!$data){
            $this->json(1,'Have not participated yet');
        }
        foreach ($data as $k=>$v){
            $data[$k]['message']=mb_substr(strip_tags(preg_replace('/\[.*?\]|\r|\n/ism','',strip_tags($v['message']))),0,30);
        }
        if(!$data){
            $this->json(1,'No more');
        }
        return $this->json(0,'ok',$data);
    }
    
    // 收藏帖子
    public function setFavore(){
        if($this->params['tid']<1){
            $this->json(1,'tid is vaild');
        }
        $subject=DB::result_first('SELECT subject from %t WHERE tid=%d',array('forum_thread',$this->params['tid']));
        if(!$subject){
            $this->json(1,'Post does not exist or has been deleted');
        }
        $data=[
            "uid"=>$this->uid,
            "id"=>$this->params['tid'],
            "idtype"=>"tid",
            "spaceuid"=>0,
            "title"=>$subject,
            "description"=>"",
            "dateline"=>time()
        ];
        if(DB::result_first('SELECT count(favid) from %t WHERE uid=%d and id=%d and idtype=%s',array('home_favorite',$this->uid,$this->params['tid'],'tid'))>0){
            $this->json(0,'ok');
        }
        if(DB::insert('home_favorite',$data)){
            updatemembercount($this->uid, array(3 => -1), true, 'jfd', 0, 'favore post', 'favore post');
            $this->json(0,'ok');
        }
        $this->json(1,'There is an error in the Favorites');
    }
    
    // 取消收藏帖子
    public function removeFavore(){
        if($this->params['tid']<1){
            $this->json(1,'tid is vaild');
        }
        $subject=DB::result_first('SELECT subject from %t WHERE tid=%d',array('forum_thread',$this->params['tid']));
        if(!$subject){
            $this->json(1,'Post does not exist or has been deleted');
        }
        if(DB::result_first('SELECT count(id) from %t WHERE uid=%d and id=%d and idtype=%s',array('home_favorite',$this->uid,$this->params['tid'],'tid'))<1){
            $this->json(0,'ok');
        }
        if(DB::delete('home_favorite',['uid'=>$this->uid,'id'=>$this->params['tid'],'idtype'=>'tid'])){
            $this->json(0,'ok');
        }
        $this->json(1,'There was an error canceling the Favorites');
    }
   
       // 发布回复内容
    public function postReply(){
        global $_G;
        if($this->params['tid']<1){
            $this->json(1,'tid is vaild');
        }
        if($this->uid<1){
            $this->json(1,'login again');
        }
        if(mb_strlen($this->params['message'])<4){
            $this->json(1,'message length is must than 4');
        }
        
        $allownum=1000;
        $vip=$this->getpay($this->uid);
        if($vip && $vip['endtime']>time()){
            $allownum=2000;
        }
        
        $rediskey='todayreply:'.date('Ymd').':'.$this->uid;
        try {
            $redis= new \Redis;
            $redis->connect('127.0.0.1',6379);
            $hasnum=(int)$redis->get($rediskey);
            if($hasnum>=$allownum){
                $this->json(1,$allownum.' replies have been received today. Please speak again tomorrow');
            }else if($hasnum===0){
                $redis->set($rediskey,$hasnum,86400);
            }
            
        } catch (\Exception $e) {
            $this->json(1,'redis error');
        }
       
       /**
        tid,fid,subject,message
       */
        // 再插入post表
            $pid = C::t('forum_post_tableid')->insert(array('pid' => ''), true);
            $lastposition=DB::result_first('SELECT position from %t WHERE tid=%d order by position desc limit %d',array('forum_post',$this->params['tid'],1));
            if(C::t('forum_post')->insert('tid:0', array(
                'tid'       => $this->params['tid'],
                'pid'       => $pid,
                'fid'       => $this->params['fid'],
                'first'     => 0,
                'author'    => DB::result_first('SELECT username from %t WHERE uid=%d',array('common_member',$this->uid)),
                'authorid'  => $this->uid,
                'subject'   => '',
                'message'   => htmlentities($this->params['message']),
                'dateline'  => time(),
                'useip'     => $_G['clientip'],
                'port'      => $_SERVER['REMOTE_PORT'],
                'bbcodeoff' => 0,
                'smileyoff' => 0,
                'htmlon' => 1,
                'position'  => $lastposition+1,
            ), true)){
                // start 奖励
                updatemembercount($this->uid, array(3 => 5), true, 'jmd', 0, 'post reply reward', 'post reply');
                $redis->set($rediskey,($hasnum+1),86400);
                // end
                $this->json(0,'ok',['redis'=>$redis->get($rediskey)]);
            }
            $this->json(1,'Reply Error');
            
    }
    // 上传头像
    public function uploadAvatar(){
        if(!isset($_FILES['img'])){
            $this->json(1,'No uploaded avatar');
        }
        if($_FILES['img']['error']>0){
            $this->json(1,'Upload error:'.$_FILES['img']['error']);
        }
        $avatar=avatar($this->uid,'middle',true);
        if(preg_match('/^http/i',$avatar)){
            $newavatar= DISCUZ_ROOT.substr($avatar,strpos($avatar,'/',8)+1);
        }else{
            $newavatar=DISCUZ_ROOT.$avatar;
        }


        $path=dirname($newavatar);
        if(!is_dir($path)){
            mkdir($path,0777,true);
        }
        if(move_uploaded_file($_FILES['img']['tmp_name'],$newavatar)){
            copy($newavatar,str_replace('middle','big',$newavatar));
            copy($newavatar,str_replace('middle','small',$newavatar));
            $this->json(0,'ok',$avatar.'?'.time());
        }
        $this->json(1,'Error uploading avatar:101',[$_FILES['img'],'new'=>$newavatar]);
    }
    
   public function login2reg(){
       $type=strtolower($this->params['type']);
       return $this->$type();
   }
   
    // 快速注册
    public function register()
    {
        global $_G;
        $username = $this->params['username'];
        // $this->json(0,$username);
        $password = daddslashes(($this->params['password']));
        $email    = $this->params['email']?daddslashes($this->params['email']):(time().'@'.mt_rand(10000,99999).'aa.cc');
        require_once './../uc_client/client.php';
        require_once './../source/class/class_member.php';
        require_once './../source/function/function_member.php';
        $uid = uc_user_register($username, $password, $email, '', '', $_G['clientip']);
        if ($uid && ($uid > 0)) {
            $setregip = DB::result_first('SELECT count(*) FROM %t WHERE ' . DB::field('ip', $_G['clientip']), array('common_regip'));
            if ($setregip == 1) {
                C::t('common_regip')->update_count_by_ip($_G['clientip']);
            } else {
                C::t('common_regip')->insert(array('ip' => $_G['clientip'], 'count' => 1, 'dateline' => $_G['timestamp']));
            }
            $init_arr = array('credits' => explode(',', '0,0,0,0,0,0,0,0,0'), 'profile' => array(), 'emailstatus' => 0);
            C::t('common_member')->insert($uid, $username, md5($password), $email, $_G['clientip'], 10, $init_arr);
            if(isset($this->params['birthday'])){
                $birthday=explode('-',$this->params['birthday']);
                DB::update('common_member_profile',[
                    'birthyear'=>$birthday[0],
                    'birthmonth'=>$birthday[1],
                    'birthday'=>$birthday[2]
                ],['uid'=>$uid]);
            }
            $data                = $this->_getuserinfo($uid);
            $data['name']        = $username;
            $data['dqlogintype'] = 'forum';
            $data['auth']        = md5(md5($uid) . 'webapp');
            $this->json(0,'ok',$data);
        } else {
            $msg = 'register error';
            switch ($uid) {
                case "-1":
                    $msg = 'username vaild';
                    break;
                case "-2":
                    $msg = 'username has registered';
                    break;
                case "-3":
                    $msg = 'has a same username';
                    break;
                case "-6":
                    $msg='the email has registered';
            }
            $this->json(1,$msg.$uid,$this->params);
        }
    }
   
    // 使用论坛帐号的登录验证
    public function login()
    {
        $user      = $this->params['username'];
        $user      = addslashes($user);
        $pass      = addslashes(($this->params['password']));
        // $pass      = substr($pass, 6, -6);
        $info      = DB::fetch_first("SELECT * FROM " . DB::table('ucenter_members') . "  WHERE username='" . $user . "'");
        $spass     = md5(md5($pass) . $info['salt']);
        $logintype = strtolower($this->params['logintype']);
        if ($spass == $info['password']) {
            $data         = $this->_getuserinfo($info['uid']);
            // 判断是否绑定qq或者微信
            $this->json(0,1,$data);
        } else {
            $this->json(1,'username or password is error'.$pass);
        }
    }
   
    

    public function getSearch()
    {
        global $_G;
        $imgurlbase=$this->urlbase;
        // if($_G['setting'] && $_G['setting']['ftp'] && $_G['setting']['ftp']['attachurl']){
        //     $imgurlbase=$_G['setting']['ftp']['attachurl'];
        // }
        $keyword = $this->params['keyword'];
        $keyword = preg_replace("/(%|_)+/i", '\\\\' . "\\1", addslashes($keyword));
        
        $start   = $this->params['size'] * ($this->params['page'] - 1);
        $contind = DB::field('fid',$this->allowshow,'in').' and '.DB::field('subject', '%' . $keyword . '%', 'like');
        $data    = DB::fetch_all("SELECT * FROM " . DB::table('forum_thread') . "  WHERE $contind order by dateline desc LIMIT " . $start . "," . $this->params['size']);
        if(!$data){
            $this->json(1,'No search for related posts');
        }
        $fidjson=$this->getForumsname();
        foreach ($data as $k=>$v){
            $data[$k]['forumname']=$fidjson[$v['fid']]['name'];
            $tmp=preg_replace(array('/\[.*?\]/ism','/&#.*?;/ism','/\s\d{4}\-\d{1,2}\-\d{1,2} \d{2}:\d{2}/i'),array('','',''),strip_tags($v['message']));
            $data[$k]['summary']=mb_substr($tmp,0,30);
            $data[$k]['author']='';
            $fm=DB::result_first('select attachment from %t WHERE tid=%d',array('forum_threadimage',$v['tid']));
            $data[$k]['cover']=$fm?($imgurlbase.'forum/'.$fm):'';
            preg_match('/\[attach.*?\](\d+)\[/i',$v['message'],$m);
            if(!$data[$k]['cover'] && $m[1]){
                $tabid=DB::result_first('select tableid from %t WHERE aid=%d',array('forum_attachment',$m[1]));
                if($tabid === 0  ||  ($tabid && $tabid!=127)){
                    $cover=DB::result_first('select attachment from %t WHERE aid=%d',array('forum_attachment_'.$tabid,$m[1]));
                    if(preg_match('/(\.jpg)|(\.png)|(\.jpeg)/i',$cover)){
                        if(!preg_match('/^http/i',$cover)){
                           $cover=$imgurlbase.'forum/'.$cover;
                        }
                        $data[$k]['cover']=$cover;
                    }
                }
            }
            if(!$data[$k]['cover'] &&  $allaids=DB::fetch_all('select * from %t where tid=%d and uid=%d ORDER by  aid  limit 20 ',array('forum_attachment',$v['tid'],$v['authorid']))){
                foreach ($allaids as $av){
                    $tmp=DB::fetch_first('select attachment,filename from %t WHERE aid=%d',array('forum_attachment_'.$av['tableid'],$av['aid']));
                    if(preg_match('/(\.jpg)|(\.png)|(\.jpeg)/i',$tmp['attachment'])){
                        $data[$k]['cover']=preg_match('/^https?/i',$tmp['attachment'])?$tmp['attachment']:($imgurlbase.'forum/'.$tmp['attachment']);
                        break;
                    }
                }
                
            }
            $data[$k]['cover']=$data[$k]['cover']?preg_replace('/img\.pindiy\.com/i','attpindiydz.oss-accelerate.aliyuncs.com',$data[$k]['cover']):'';
        }
        
        
        
        // 将搜索结果存到 common_searchindex 表，如果是pc先搜索，则正常，如果是app先搜索，
        if($has=DB::fetch_first('select searchid,num from %t WHERE keywords = %s order by searchid desc',array('common_searchindex',$keyword))){
            $num=(int)$has['num']+1;
            // 是否原本已存在app的搜索，之后pc又新增了，此时需要合并 num
            $apphas=DB::fetch_first('select searchid,num from %t WHERE keywords=%s and searchid != %d',array('common_searchindex',$keyword,$has['searchid']));
            if($apphas){
                DB::delete('common_searchindex',['searchid'=>$apphas['searchid']]);
                $num+=(int)$apphas['num'];
            }
            
            DB::update('common_searchindex',['num'=>$num],['searchid'=>$has['searchid']]);
        }else{
            DB::insert('common_searchindex',[
               "srchmod"=>2, 
               "keywords"=>$keyword, 
               "searchstring"=>'', 
               "useip"=>$_SERVER['REMOTE_ADDR'], 
               "uid"=>intval($this->uid), 
               "dateline"=>time(), 
               "expiration"=>time()+864000, 
               "threadsortid"=>0, 
               "num"=>0, 
               "ids"=>0 
            ]);
        }
        
        $this->json(0,'ok',$data);
    }
    // 更新信息
    public function updateUserinfo(){
        if($this->uid<1){
            $this->json(1,'Not yet logged in');
        }
        $this->json(0,'ok',$this->_getuserinfo($this->uid));
    }
    
    // 获取 视频推荐
    public function getYoutube(){
        $start   = $this->params['size'] * ($this->params['page'] - 1);
        $data=DB::fetch_all("select * from %t   order by dateline desc limit %d,%d",[
			   	"pindiysp_iframe",
			   	$start,
			   	$this->params['size']
		   ]);
			if(!$data){
			  $this->json(1,'nothing data');
			}else{
			  $this->json(0,'ok',$data);
		   }
    }
    
    public function getyoutube2(){
        // $this->json(0,'ok',['a'=>1,'start'=>1]);
        $start   = $this->params['size'] * ($this->params['page'] - 1);
        // $this->json(0,'ok',['a'=>1,'start'=>$start]);
        $data=DB::fetch_all("select * from %t   order by dateline desc limit %d,%d",[
			   	"pindiysp_iframe",
			   	$start,
			   	$this->params['size']
		]);
		header('Content-Type:application/json;charset=utf-8');
		echo json_encode([
		   "code"=>$data?0:1,
		   "msg"=>$data?'ok':"no",
		   "data"=>$data?$data:[]
		]);
		exit;
			if(!$data){
			  $this->json(1,'nothing data');
			}else{
			 // $this->json(0,'ok',['a'=>1]);
		   }
    }
    
    // 检测版本更新
    public function initinfo(){
        $version=$this->params['version'];
        $platform=$this->params['platform'];
        
        $update=parse_ini_file(__DIR__.'/update.ini');
        
        // $android='3.2.0';
        // $androidurl='https://www.baidu.com';
        
        // $ios='3.2.1';
        // $iosurl='';
        
        
        $yes=version_compare($update[$platform],$version);
        if($yes<1){
            $this->json(1,'no');
        }
        
            $this->json(0,'ok',[
               "version"=>$version,
               "platform"=>$platform,
               "force"=>$update['force'],
               "url"=>$update[$platform.'url']
            ]);
    }
    
    // 获取用户今日的任务情况
    public function getReward(){
        if($this->uid<1){
            $this->json(1,'login again');
        }
        $adids=explode(',',$this->params['adids']);
        
        $date=$this->params['date'];
        
        if($adids && $date){
            $data=[];
            $redis= new \Redis;
            $redis->connect('127.0.0.1',6379);
            foreach ($adids as $adid){
                if($cache=$redis->get("{$date}:adid:{$adid}:uid:".$this->uid)){
                    $data[]=json_decode($cache,true);
                }
            }
            $this->json(0,'ok',$data);
        }
        $this->json(1,'no');
    }
    // 获取用户今日的任务情况
    public function getRewardv2(){
        if($this->uid<1){
            $this->json(1,'login again');
        }
        $adids=explode(',',$this->params['adids']);
        
        $date=$this->params['date'];
        
        if($adids && $date){
            $data=[];
            $redis= new \Redis;
            $redis->connect('127.0.0.1',6379);
            // 今天已经完成的广告数量
            $hastodayend=(int)$redis->get("{$date}:uid:".$this->uid);
            $this->json(0,'ok',['num'=>$hastodayend]);
        }
        $this->json(1,'no');
    }
    
    // 用户完成广告任务进行奖励
    public function reward(){
        // file_put_contents(__DIR__."/ceshi.log",var_export($_SERVER,true)."\n",FILE_APPEND);
        global $_G;
        if($this->uid<1){
            $this->json(1,'login again');
        }
        
        $jldata=json_decode($this->params['jldata'],true);
        $adid=$this->params['adid'];
        $date=$this->params['date'];

        if($jldata && $adid && $date){
            // start 奖励
            $jlnum=intval($jldata['amount']);
            if(isset($this->params['isvip']) && $this->params['isvip']==1){
                $jlnum=$jlnum*2;
            }
            // updatemembercount($this->uid, array(3 => $jlnum), true, 'jmd', 0, 'task reward', 'taskreward');
            // end
            $redis= new \Redis;
            $redis->connect('127.0.0.1',6379);
            $today=$redis->get($date.":adid:{$adid}:uid:".$this->uid);
            if($today){
                $today=json_decode($today,true);
                $today=$today['today'];
            }
            $redis->set($date.":adid:{$adid}:uid:".$this->uid,json_encode([
                "adid"=>$adid,
                "today"=>$today+1,
                "os"=>preg_match('/iOS/',$_SERVER['HTTP_USER_AGENT'])?'ios':'android'
            ]),86400);
            // 今天已经完成的广告数量，新版v2
            $redis->set($date.":uid:".$this->uid,$this->params['todaycount'],86400);
            $redis->set($date.":os:".$this->uid,preg_match('/iOS/',$_SERVER['HTTP_USER_AGENT'])?'ios':'android',86400);
            $this->json(0,'ok',$jldata);
        }
        $this->json(1,'no');
    }


    private function _getuserinfo($uid)
    {
        global $_G;
        loadcache('plugin');
        $data               = array();
        $data['uid']          = $uid;
        $data['access_token']         = preg_replace('/\+/ism','plusadd',authcode($uid.":".time(),'ENCODE','webapp',864000));
        $data['userinfo']     = DB::fetch_first("SELECT * FROM %t WHERE uid=%d", array('common_member', $uid));
        $data['saltkey']=$_G['cookie']['saltkey'];
        $data['webauth']=authcode("{$data['password']}\t{$uid}", 'ENCODE','',8640000);
        $data['userinfo']['groupname']=DB::result_first('SELECT grouptitle from %t WHERE groupid=%d',array('common_usergroup',$data['userinfo']['groupid']));
        $jinbi=DB::fetch_first('SELECT * from %t WHERE uid=%d',array('common_member_count',$uid));
        $data['userinfo']['jifen']=[];
        foreach ($_G['setting']['extcredits'] as $id=>$v){
            if($id<4 && $v['title']){
                $data['userinfo']['jifen'][$v['title']]=$jinbi['extcredits'.$id];
            }
        }
        $data['userinfo']['avatar']=$avatar=avatar($uid, 'middle', true);
        if(!is_file(DISCUZ_ROOT.'.'.substr($avatar, strpos($avatar, "/",8)))){
            $data['userinfo']['avatar']='';
        }
        $pay=$this->getpay($uid);
        if($pay){
            $data['currentvip']=$pay;
        }
        return $data;
    }
    
    // 支付相关日志记录
    private function logs(){
        $name=__DIR__.'/log/'.date('Ymd');
        if(!is_dir($name)){
            mkdir($name,0777,true);
        }
        $name.='/'.$this->uid.'.log';
        // 日志信息
        file_put_contents($name,
            date('Ymd H:i:s')." : \n".
            var_export($this->params,true)."\n\n"
        ,FILE_APPEND);
    }
    // 统一将订单插入数据库
    private function insertorder($data=[]){
        try {
            $orderinfo=!is_array($this->params['orderinfo'])?json_decode($this->params['orderinfo'],true):$this->params['orderinfo'];
            $orderinfo['os']=$this->params['os']?$this->params['os']:'unknown';
            if(is_array($orderinfo['product'])){
                $orderinfo['product']=json_encode($orderinfo['product']);
            }
            if(is_array($orderinfo['result'])){
                $orderinfo['result']=json_encode($orderinfo['result']);
            }
            DB::insert('apporderinfo',array_merge($orderinfo,$data) );
        } catch (\Exception $e) {
            file_put_contents(__DIR__.'/log/'.date('Ymd').'ordersql-error.log',$e->getMessage()."\n".var_export($orderinfo,true)."\n".var_export($this->params,true)."\n\n",FILE_APPEND);
        }
    }
    
    // 内部调用获取当前用户的pay记录
    private function getpay($uid){
        return DB::fetch_first('select * from %t where uid=%d',array('appvip',$uid));
    }
    
    
    // 购买vip android ios 统一 购买
    public function buyvip(){
        if($this->uid<1){
            $this->json(1,'login again');
        }
        // 日志
        $this->logs();
        
        if($_POST['type']>=6){
            return $this->rechargemoney();
        }
         if($id=DB::result_first('select id from %t where uid=%d',array('appvip',$this->uid))){
            // 已存在则更新
            DB::update('appvip',[
                "type"=>(int)$this->params['type'],
                "endtime"=>(int)$this->params['endtime'],
                "update_time"=>time()
            ],[
                "uid"=>$this->uid    
            ]);
        }else {
            // 插入
            DB::insert('appvip',[
                "type"=>(int)$this->params['type'],
                "endtime"=>(int)$this->params['endtime'],
                "update_time"=>time(),
                "uid"=>$this->uid
            ]);
        }
        
        $this->insertorder();
        // 奖励money
        // updatemembercount($this->uid, array(2 => ceil($this->params['price'])), true, 'jmd', 0, 'buy vip at app', 'buy vip');
        $this->json(0,'ok');
    }
    // 充值money
    public function rechargemoney(){
        if($this->params['price']<1){
            $this->json(1,'error price');
        }
        $num=10;
        // 记录日志
        $this->logs();
        // 存储充值订单信息
        $this->insertorder(['num'=>$num]);
        // 奖励money
        updatemembercount($this->uid, array(2 => $num), true, 'jmd', 0, 'recharge money', 'recharge');
        
        $this->json(0,'ok');
    }
    
    // 错误的vip订单信息处理
    public function errorpay(){
        if($this->uid<1){
            $this->json(1,'login again');
        }
        // 日志
        $this->logs();
        // 存储订单信息
        $this->insertorder();
        $this->json(0,'ok');
    }
    
    
    // 保存googlepay购买记录
    public function googlepay(){
        $this->buyvip();
    }
    // 保存iospay购买记录
    public function iospay(){
        $this->buyvip();
    }
    // 错误的vip订单信息处理
    public function errorvippay(){
        $this->errorpay();
    }
    
    // 错误的充值订单信息处理
    public function errorrechargepay(){
        $this->errorpay();
    }
    
    // 举报
    public function jubao(){
        try {
            $redis= new \Redis;
            $redis->connect('127.0.0.1',6379);
            $date=date('Ymd');
            if($redis->get('myjubao:'.$date.':'.$this->uid)){
                $this->json(1,'You have complained today. Please come back in 24 hours');
            }
            $redis->set('myjubao:'.$date.':'.$this->uid,1,86400);
            file_put_contents(__DIR__.'/jubao/'.$date.'.txt',
                json_encode($this->params)."\n",
            FILE_APPEND);
            $tid=(int)$this->params['tid'];
            if($tid>0){
                
                if(!$redis->sismember('jubaotidlist',$tid)){
                    $redis->sadd('jubaotidlist',$tid);
                    $redis->expire('jubaotidlist',864000);
                }
            }
        } catch (\Exception $e) {
            $this->json(1,'Error, please try again later');
        }    
        $this->json(0,'ok');
        
    }

    private function json($code,$msg,$data=[])
    {
        header('Content-Type: application/json; charset=utf-8');
        echo json_encode([
            "code"=>$code,
            "msg"=>$msg,
            "data"=>$data
        ]);
        exit;
    }
    private function _isutf8($str)
    {
        $len = strlen($str);
        for ($i = 0; $i < $len; $i++) {
            $c = ord($str[$i]);
            if ($c > 128) {
                if (($c > 247)) {
                    return false;
                } elseif ($c > 239) {
                    $bytes = 4;
                } elseif ($c > 223) {
                    $bytes = 3;
                } elseif ($c > 191) {
                    $bytes = 2;
                } else {
                    return false;
                }

                if (($i + $bytes) > $len) {
                    return false;
                }

                while ($bytes > 1) {
                    $i++;
                    $b = ord($str[$i]);
                    if ($b < 128 || $b > 191) {
                        return false;
                    }

                    $bytes--;
                }
            }
        }
        return true;
    }
}
